package PrefixSum;

//https://leetcode.cn/problems/product-of-array-except-self/description/
public class l_238 {
    public int[] productExceptSelf(int[] nums) {
        //默认前缀和是以1开始计数, 此题以0开始
        int n = nums.length;
        //f[i]表示nums[0] + ... + nums[i-1]的乘积
        int[] f = new int[n];
        //g[i]表示nums[i+1] + ... + nums[n-1]的乘积
        int[] g = new int[n];
        int[] ans = new int[n];

        //因为是乘积所以需要这一步
        f[0] = g[n - 1] = 1;
        for(int i = 1; i < n; i++)
            f[i] = f[i - 1] * nums[i - 1]; //初始化和默认前缀和不同
        for(int i = n - 2; i >= 0; i--)
            g[i] = g[i + 1] * nums[i + 1]; //初始化和默认前缀和不同

        for(int i = 0; i < n; i++)
            ans[i] = f[i] * g[i];
        return ans;
    }
}
